<template>
  <div>
    <span>导出报告</span>
  </div>
</template>

<script>
import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
// import JSZip from 'jszip'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'
import XLSX from 'xlsx'

export default {
  name: 'BlockReport',
  data () {
    return {
      name: '',
      errName: ''
    }
  },
  components: {
    // XLSX
  },
  methods: {
    async init (id) {
      const res = await this.$http('blockVerifyAdd', {
        id: id,
        del_flag: '0'
      })

      this.word(id)
    },
    // 更改报告信息
    async writerUpdate (id) {
      const res = await this.$http('blockLogUp', {
        id: id,
        del_flag: '0'
      })
      this.word(id)
    },
    async word (id) {
      try {
        const res = await this.$http('blockVerifyObj', {
          id: id,
        })

        const data = res
        let projectInfo = []
        let checkInfo = ''
        projectInfo.push(JSON.parse(data.data_info))
        let date = new Date().toLocaleString()
        this.name = projectInfo[0].project_name + ' ' + date
        // .replaceAll(new RegExp(/[/_:]/g),'-')
        // vgiterify_package_name
        if (parseFloat(projectInfo[0].money) > parseFloat(projectInfo[0].decrease_amount)) {
          checkInfo = '本项目共' + projectInfo[0].packageNum + '个包组，申报运维资金' + projectInfo[0].third_amount + '万元，经审核，运维资金调整为' +
            projectInfo[0].third_amount + '万元，核减资金' + 0 + '万元。'
        } else {
          checkInfo = '经审核，运维资金无调整。'
        }
        let var1 = ''
        let var2 = ''
        let var3 = ''
        let var4 = ''
        let packageList = []
        if (data.data_json) {
          packageList = JSON.parse(data.data_json)
          packageList.forEach((item1, index1) => {
            item1.packInfo = '包组:' + (index1 + 1) + '：' + item1.verify_package_name + '，包组预算:' + item1.pack_service_amount_check
            item1.children.forEach((item2, index2) => {
              item2.subjectInfo = '标的:' + (index2 + 1) + '：' + item2.verify_subject_name + '，预算标准:' +
                item2.verify_subject_apply_money + '，运维期限：（' + item2.verify_subject_serve_date + '）个月，标的类型：' +
                (item2.verify_subject_serve_type_other == 'true'
                  ? this.$util.ITRename(item2.verify_subject_serve_type)(item2.verify_subject_serve_type_other)
                  : this.$util.ITRename(item2.verify_subject_serve_type))
              item2.subjectList = item2.verify_subject_list

              item2.subjectServe = item2.verify_subject_serve
              item2.subjectServeSub = item2.verify_subject_serve_sub

              if (item2.type.indexOf('其他') > -1) {
                item2.typeCopy = item2.type + '-' + item2.type_other
              } else {
                item2.typeCopy = item2.type
              }
            })
          })
          var1 = '工程量清单：'
          var2 = '运维服务标准：'
          var3 = '服务内容：'
          var4 = '指标：'
        } else {
          packageList = JSON.parse(data.fill_list)
          packageList.forEach((item1, index1) => {
            item1.packInfo = ''
            item1.verify_package_basis = ''
            item1.children.forEach((item2, index2) => {
              item2.subjectInfo = ''
              item2.verify_subject_basic = ''
              item2.subjectList = ''
              item2.verify_subject_list_basis = ''
              item2.subjectServe = ''
              item2.verify_subject_serve_basis = ''
              item2.subjectServeSub = ''
              item2.verify_subject_serve_sub_basis = ''
              if (item2.type.indexOf('其他') > -1) {
                item2.typeCopy = item2.type + '-' + item2.type_other
              } else {
                item2.typeCopy = item2.type
              }
            })
          })
        }

        let obj = {
          var1,
          var2,
          var3,
          var4,
          projectInfo,
          checkInfo,
          packageList
        }
        this.makeWord(obj)
      } catch (err) {
        this.$tips.error('导出失败，请检查项目是否完全填写' + '\n' + '错误：' + err)
      }
    },
    makeWord (item) {
      // let ImageModule = require('docxtemplater-image-module-free')
      JSZipUtils.getBinaryContent('/static/doc/block-report.docx', (error, content) => {
        // verify-report.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
        // 抛出异常
        if (error) {
          throw error
        }
        // 创建一个PizZip实例，内容为模板的内容
        let zip = new PizZip(content)
        // 创建并加载docxtemplater实例对象
        let doc = new Docxtemplater(zip, { linebreaks: true }, { paragraphLoop: true })
        // linebreaks 开启换行  paragraphLoop  清除多余间隔
        // let doc = new Docxtemplater()
        // doc.loadZip(zip)
        // 设置模板变量的值
        doc.setData(item, this.nullGetter)

        try {
          // 用模板变量的值替换所有模板变量
          doc.render()

        } catch (error) {
          // 抛出异常
          let e = {
            message: error.message,
            name: error.name,
            stack: error.stack,
            properties: error.properties
          }
          throw error
        }
        // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
        let out = doc.getZip().generate({
          type: 'blob',
          mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        })
        // 将目标文件对象保存为目标类型的文件，并命名
        saveAs(out, this.name + '.docx')
      })
    },
    before (file) { // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者 Promise 则停止上传
      let reader = new FileReader() // 读取操作就是由它完成.
      reader.readAsBinaryString(file)// 读取文件的内容,也可以读取文件的URL
      reader.onload = function (evt) {
        // 当读取完成后回调这个函数,然后此时文件的内容存储到了result中,直接操作即可
        var data = evt.target.result
        var workbook = XLSX.read(data, {
          type: 'binary'
        }) // 以二进制流方式读取得到整份excel表格对象
      }

      return false
    },
    getInitErrorMsg (data) {
      let parse = JSON.parse(data.errmsg)
      let errormsg = '操作失败 <br/>'
      for (let i = 0; i < parse.length; i++) {
        if (parse[i].projectName == null) {
          errormsg = '该项目为空'
          return errormsg
        }
        if (parse[i].packageName == null) {
          errormsg = '该项目包组为空'
          return errormsg
        }
        if (parse[i].subjectName == null) {
          errormsg = '该项目标的为空'
          return errormsg
        }
        if (parse[i].content == null) {
          errormsg = '该项目招标技术参数为空'
          return errormsg
        }
        if (parse[i].type == null) {
          errormsg = '该项目标的类型为空'
          return errormsg
        }
      }
    }
  }
}
</script>

<style scoped>
/*.wrap {*/
/*position: fixed;*/
/*top: 0;*/
/*left: 0;*/
/*width: 100%;*/
/*bottom: 0;*/
/*}*/

.line-scale-pulse-out-rapid.success > div {
  background-color: #4caf50;
}

.line-scale-pulse-out-rapid.null > div {
  background-color: #f44336;
}

.line-scale-pulse-out-rapid.fail > div {
  background-color: #ff9800;
}

.line-scale-pulse-out-rapid > div {
  width: 2px;
  height: 20px;
  display: inline-block;
  border-radius: 2px;
  margin: 2px;
  background-color: #fff;
  vertical-align: middle;
  -webkit-animation: line-scale-pulse-out-rapid 0.9s -0.5s infinite cubic-bezier(0.11, 0.49, 0.38, 0.78);
  animation: line-scale-pulse-out-rapid 0.9s -0.5s infinite cubic-bezier(0.11, 0.49, 0.38, 0.78);
}

.line-scale-pulse-out-rapid > div:nth-child(2),
.line-scale-pulse-out-rapid > div:nth-child(4),
.line-scale-pulse-out-rapid > div:nth-child(6) {
  -webkit-animation-delay: -0.25s !important;
  animation-delay: -0.25s !important;
}

.line-scale-pulse-out-rapid > div:nth-child(1),
.line-scale-pulse-out-rapid > div:nth-child(7) {
  -webkit-animation-delay: 0s !important;
  animation-delay: 0s !important;
}

@-webkit-keyframes line-scale-pulse-out-rapid {
  0%,
  90% {
    -webkit-transform: scaley(1);
    transform: scaley(1);
  }
  80% {
    -webkit-transform: scaley(0.3);
    transform: scaley(0.3);
  }
}

@keyframes line-scale-pulse-out-rapid {
  0%,
  90% {
    -webkit-transform: scaley(1);
    transform: scaley(1);
  }
  80% {
    -webkit-transform: scaley(0.3);
    transform: scaley(0.3);
  }
}
</style>
